﻿using IDAdmin.Common;
using IDAdmin.Lib.DataLayer;
using IDAdmin.Lib.UI;
using IDAdmin.Lib.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace IDAdmin.Pages
{
    public partial class LossAndSaveLevelStatistics : BasePage
    {
        public const string hostName = "222.255.177.27";
        public const int port = 9823;

        public LossAndSaveLevelStatistics()
            : base(Lib.AppFunctions.LOSSANDSAVELEVEL)
        {

        }
        protected override void Page_Load(object sender, EventArgs e)
        {
            if (!IsLogin())
            {
                RedirectToLogOn();
            }
            else if (!CheckRight())
            {
                RedirectToDeniedMessage();
            }
        }

        private Table getLevelLoss(List<Au> auData)
        {
            List<Au> auList = new List<Au>(auData.Count);

            auData.ForEach((item) =>
            {
                auList.Add(new Au(item));
            });

            //List<Ccu> ccuList = new List<Ccu>(ccuData.Count);

            //ccuData.ForEach((item) =>
            //{
            //ccuList.Add(new Ccu(item));
            //});

            foreach (Au auItem in auList)
            {
                auItem.Timestamp = ConverterWorkData.truncateTime(auItem.Timestamp, "dd/MM/yyyy");
            }

            var timeList = (from tb2 in auList select tb2.Timestamp).Distinct().ToList();
            timeList.Sort();

            string countTime = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(IDAdmin.Common.ConverterWorkData.convertStringToDateTime(txtCountDate.Text), DateTimeKind.Local).ToString(), "dd/MM/yyyy");

            var accountAtTimeList = new[] { new { Account = "" } }.ToList();
            accountAtTimeList.RemoveAt(0);
            foreach (var item in auList)
            {//gamezone=2491372 tân vương
                if (item.Timestamp.Equals(countTime) && item.GameZone.Equals("1004"))
                {
                    accountAtTimeList.Add(new { Account = item.Account });
                }
            }
            accountAtTimeList.Distinct();


            var checkDayNum = (from tb in timeList.AsParallel() where tb.CompareTo(countTime) > 0 select tb).Count().ToString();

            List<LevelAndPeopleNum> lvAndPeoNumList = new List<LevelAndPeopleNum>();

            if (int.Parse(checkDayNum) >= 7)
            {
                DateTime dtTemp = ConverterWorkData.kindUnixTimeStampToKindDateTime(double.Parse(countTime), DateTimeKind.Local, DateTimeKind.Local);
                List<DateTime> sevenDayAfterList = new List<DateTime>();
                //sevenDayBeforeList.Add(dtTemp);
                for (int j = 1; j <= 7; j++)
                {
                    sevenDayAfterList.Add(dtTemp.AddDays(j));
                }

                //DateTime dtAtDaySeven = dtTemp.AddDays(-7);
                //string timeStampAtDaySeven = truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dtAtDaySeven, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                int count = 0;
                var accountNotLoginAtTimeList = new[] { new { Account = "" } }.ToList();
                accountNotLoginAtTimeList.RemoveAt(0);
                foreach (var item in accountAtTimeList)
                {
                    int numLoop = 0;
                    foreach (DateTime dtItem in sevenDayAfterList)
                    {
                        string dtCurrent = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dtItem, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                        var hasLogin = (from tb in auList.AsParallel() where tb.Account.Equals(item.Account) && tb.Timestamp.Equals(dtCurrent) select tb).Count().ToString();
                        if (int.Parse(hasLogin) <= 0)
                        {
                            numLoop++;
                        }
                    }
                    if (numLoop.Equals(7))
                    {
                        accountNotLoginAtTimeList.Add(item);
                        count++;
                    }
                }
                var accountAndLevelList = new[] { new { Account = "", Level = "" } }.ToList();
                accountAndLevelList.RemoveAt(0);

                foreach (var account in accountNotLoginAtTimeList)
                {
                    string url = "http://{0}:{1}/getCharidName?gosuAccount={2}&game=38&zone=1004";
                    url = string.Format(url, hostName, port, account.Account);
                    string result = HttpHelper.HttpSocket(url, 26);
                    if (string.IsNullOrEmpty(result) == false)
                    {
                        if (result.Substring(0, 1).Equals("0"))
                        {
                            JavaScriptSerializer jss = new JavaScriptSerializer();
                            CharidName cin = jss.Deserialize<CharidName>(result.Substring(2, result.IndexOf("}", result.IndexOf("name")) - 1));
                            string otherUrl = "http://{0}:{1}/getRoleMessage?charID={2}&game=38&zone=1004";
                            otherUrl = string.Format(otherUrl, hostName, port, cin.charid);
                            string otherResult = HttpHelper.HttpSocket(otherUrl, 26);
                            if (string.IsNullOrEmpty(otherResult) == false)
                            {
                                if (otherResult.Substring(0, 1).Equals("0"))
                                {
                                    RoleMessage rm = jss.Deserialize<RoleMessage>(otherResult.Substring(2, otherResult.IndexOf("}", otherResult.IndexOf("onlinetime")) - 1));
                                    accountAndLevelList.Add(new { Account = account.Account, Level = rm.level });
                                }
                            }
                            else
                            {
                                messageLB.Text = "Kết quả trả về gọi api là chuỗi rỗng!";
                                return new Table();
                                //lvAndPeoNumList = new List<LevelAndPeopleNum>();
                                //goto Table;
                            }
                        }
                    }
                    else
                    {
                        //lvAndPeoNumList = new List<LevelAndPeopleNum>();
                        // goto Table;
                        messageLB.Text = "Kết quả trả về gọi api là chuỗi rỗng!";
                        return new Table();
                    }
                }
                lvAndPeoNumList = (from tb in accountAndLevelList group tb by new { tb.Level } into grp select new LevelAndPeopleNum { Level = grp.Key.Level, PeopleNum = grp.Count().ToString() }).OrderBy(o => int.Parse(o.Level)).ToList();
            }

            // DataTable dt = ConverterWorkData.ToDataTable(lvAndPeoNumList, 3, 0);

            Table table = new Table();
            table.CssClass = "table1";
            table.CellSpacing = 1;
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                {     
                    UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                     UIHelpers.CreateTableCell("Level",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                       UIHelpers.CreateTableCell("People Number",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                    //UIHelpers.CreateTableCell("CcuServerList",Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[5].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[6].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader")
                }
            );

            table.Rows.Add(rowHeader);
            try
            {
                if (lvAndPeoNumList == null || lvAndPeoNumList.Count == 0)
                {
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    //labelCountOfUser.Text = string.Format("{0:N0}", dt.Rows.Count);
                    string css;
                    int stt = 0;
                    foreach (LevelAndPeopleNum dr in lvAndPeoNumList)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();
                        row.Cells.AddRange
                        (
                            new TableCell[]
                           {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Level),HorizontalAlign.Left,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.PeopleNum),HorizontalAlign.Left,css)
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[5].ColumnName]),HorizontalAlign.Left,css),
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[6].ColumnName]),HorizontalAlign.Left,css),

                           }
                        );

                        table.Rows.Add(row);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return table;
        }

        private Table getLevelSave(List<Au> auData)
        {
            List<Au> auList = new List<Au>(auData.Count);

            auData.ForEach((item) =>
            {
                auList.Add(new Au(item));
            });

            foreach (Au auItem in auList)
            {
                auItem.Timestamp = ConverterWorkData.truncateTime(auItem.Timestamp, "dd/MM/yyyy");
            }

            var timeList = (from tb2 in auList select tb2.Timestamp).Distinct().ToList();
            timeList.Sort();

            string countTime = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(IDAdmin.Common.ConverterWorkData.convertStringToDateTime(txtCountDate.Text), DateTimeKind.Local).ToString(), "dd/MM/yyyy");

            var checkDayNum = (from tb in timeList.AsParallel() where tb.CompareTo(countTime) < 0 select tb).Count().ToString();

            List<LevelAndPeopleNum> lvAndPeoNumList = new List<LevelAndPeopleNum>();


            if (int.Parse(checkDayNum) >= 7)
            {
                DateTime dtTemp = ConverterWorkData.kindUnixTimeStampToKindDateTime(double.Parse(countTime), DateTimeKind.Local, DateTimeKind.Local);
                List<DateTime> sevenDayBeforeList = new List<DateTime>();
                //sevenDayBeforeList.Add(dtTemp);
                for (int j = 1; j <= 7; j++)
                {
                    sevenDayBeforeList.Add(dtTemp.AddDays(-j));
                }
                List<List<string>> dauAtTimeList = new List<List<string>>();
                var dauGroupAccountTimeStampList = (from tb in auList.AsParallel() group tb by new { tb.Account, tb.Timestamp } into grp select new { grp.Key.Account, grp.Key.Timestamp });
                foreach (DateTime dtItem in sevenDayBeforeList)
                {
                    string dtCurrent = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dtItem, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                    dauAtTimeList.Add(dauGroupAccountTimeStampList.AsParallel().Where(w => w.Timestamp.Equals(dtCurrent)).Select(s => s.Account).ToList());
                }

                List<string> unionSevenDayBefore = new List<string>();
                foreach (List<string> item in dauAtTimeList)
                {
                    //var listTemp = (from tb in item select tb);//.Union(from tb1 in unionDaySevenDayBefore select tb1).ToList();
                    foreach (var itemi in item)
                    {
                        unionSevenDayBefore.Add(itemi);
                    }

                }
                var a7List = unionSevenDayBefore.AsParallel().Distinct();


                var accountAndLevelList = new[] { new { Account = "", Level = "" } }.ToList();
                accountAndLevelList.RemoveAt(0);

                foreach (var account in a7List)
                {
                    string url = "http://{0}:{1}/getCharidName?gosuAccount={2}&game=38&zone=1004";
                    url = string.Format(url, hostName, port, account);
                    string result = HttpHelper.HttpSocket(url, 26);
                    if (string.IsNullOrEmpty(result) == false)
                    {
                        if (result.Substring(0, 1).Equals("0"))
                        {
                            JavaScriptSerializer jss = new JavaScriptSerializer();
                            CharidName cin = jss.Deserialize<CharidName>(result.Substring(2, result.IndexOf("}", result.IndexOf("name")) - 1));
                            string otherUrl = "http://{0}:{1}/getRoleMessage?charID={2}&game=38&zone=1004";
                            string otherResult = "";
                            if (string.IsNullOrEmpty(cin.charid))
                            {
                                otherResult = "5|";
                            }
                            else
                            {
                                otherUrl = string.Format(otherUrl, hostName, port, cin.charid);
                                otherResult = HttpHelper.HttpSocket(otherUrl, 26);
                            }

                            if (string.IsNullOrEmpty(otherResult) == false)
                            {
                                if (otherResult.Substring(0, 1).Equals("0"))
                                {
                                    RoleMessage rm = jss.Deserialize<RoleMessage>(otherResult.Substring(2, otherResult.IndexOf("}", otherResult.IndexOf("onlinetime")) - 1));
                                    accountAndLevelList.Add(new { Account = account, Level = rm.level });
                                }
                            }
                            else
                            {
                                messageLB.Text = "Kết quả trả về gọi api là chuỗi rỗng!";
                                return new Table();
                            }
                        }
                    }
                    else
                    {
                        messageLB.Text = "Kết quả trả về gọi api là chuỗi rỗng!";
                        return new Table();
                    }
                }
                //messageLB.Text = a7List.Count().ToString();
                lvAndPeoNumList = (from tb in accountAndLevelList group tb by new { tb.Level } into grp select new LevelAndPeopleNum { Level = grp.Key.Level, PeopleNum = grp.Count().ToString() }).OrderBy(o => int.Parse(o.Level)).ToList();
            }

            //DataTable dt = ConverterWorkData.ToDataTable(lvAndPeoNumList, 3, 0);

            Table table = new Table();
            table.CssClass = "table1";
            table.CellSpacing = 1;
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                {     
                    UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                     UIHelpers.CreateTableCell("Level",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                       UIHelpers.CreateTableCell("People Number",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                    //UIHelpers.CreateTableCell("CcuServerList",Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[5].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[6].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader")
                }
            );

            table.Rows.Add(rowHeader);
            try
            {
                if (lvAndPeoNumList == null || lvAndPeoNumList.Count == 0)
                {
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    //labelCountOfUser.Text = string.Format("{0:N0}", dt.Rows.Count);
                    string css;
                    int stt = 0;
                    foreach (LevelAndPeopleNum dr in lvAndPeoNumList)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();
                        row.Cells.AddRange
                        (
                            new TableCell[]
                           {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Level),HorizontalAlign.Left,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.PeopleNum),HorizontalAlign.Left,css)
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[5].ColumnName]),HorizontalAlign.Left,css),
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[6].ColumnName]),HorizontalAlign.Left,css),

                           }
                        );

                        table.Rows.Add(row);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return table;
        }

        private Table getLevelSave2(List<Au> auData)
        {
            List<Au> auList = new List<Au>(auData.Count);

            auData.ForEach((item) =>
            {
                auList.Add(new Au(item));
            });

            foreach (Au auItem in auList)
            {
                auItem.Timestamp = ConverterWorkData.truncateTime(auItem.Timestamp, "dd/MM/yyyy");
            }

            var timeList = (from tb2 in auList select tb2.Timestamp).Distinct().ToList();
            timeList.Sort();

            string countTime = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(IDAdmin.Common.ConverterWorkData.convertStringToDateTime(txtCountDate.Text), DateTimeKind.Local).ToString(), "dd/MM/yyyy");

            var checkDayNum = (from tb in timeList.AsParallel() where tb.CompareTo(countTime) <= 0 select tb).Count().ToString();

            List<LevelAndPeopleNum> lvAndPeoNumList = new List<LevelAndPeopleNum>();


            if (int.Parse(checkDayNum) >= 7)
            {
                DateTime dtTemp = ConverterWorkData.kindUnixTimeStampToKindDateTime(double.Parse(countTime), DateTimeKind.Local, DateTimeKind.Local);
                DateTime sixthDay = dtTemp.AddDays(-6);
                string dtCurrentTS = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(dtTemp, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                string sixthDayTS = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(sixthDay, DateTimeKind.Local).ToString(), "dd/MM/yyyy");
                var a7List = auList.Where(w => int.Parse(w.Timestamp) >= int.Parse(sixthDayTS) && int.Parse(w.Timestamp) <= int.Parse(dtCurrentTS)).Select(s => s.Account).Distinct().ToList();

                var accountAndLevelList = new[] { new { Account = "", Level = "" } }.ToList();
                accountAndLevelList.RemoveAt(0);

                foreach (var account in a7List)
                {
                    string url = "http://{0}:{1}/getCharidName?gosuAccount={2}&game=38&zone=1004";
                    url = string.Format(url, hostName, port, account);
                    string result = HttpHelper.HttpSocket(url, 26);
                    if (string.IsNullOrEmpty(result) == false)
                    {
                        if (result.Substring(0, 1).Equals("0"))
                        {
                            JavaScriptSerializer jss = new JavaScriptSerializer();
                            CharidName cin = jss.Deserialize<CharidName>(result.Substring(2, result.IndexOf("}", result.IndexOf("name")) - 1));
                            // string level = LevelWebDB.getLevel(cin.charid,"2015-03-12 00:00:00",dtTemp.ToString("yyyy-MM-dd") + " 23:59:59");
                            // accountAndLevelList.Add(new { Account = account, Level = level });
                        }
                    }
                    else
                    {
                        messageLB.Text = "Kết quả trả về gọi api là chuỗi rỗng!";
                        return new Table();
                    }
                }
                //messageLB.Text = a7List.Count().ToString();
                lvAndPeoNumList = (from tb in accountAndLevelList group tb by new { tb.Level } into grp select new LevelAndPeopleNum { Level = grp.Key.Level, PeopleNum = grp.Count().ToString() }).OrderBy(o => int.Parse(o.Level)).ToList();
            }

            //DataTable dt = ConverterWorkData.ToDataTable(lvAndPeoNumList, 3, 0);

            Table table = new Table();
            table.CssClass = "table1";
            table.CellSpacing = 1;
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                {     
                    UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                     UIHelpers.CreateTableCell("Level",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                       UIHelpers.CreateTableCell("People Number",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                    //UIHelpers.CreateTableCell("CcuServerList",Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[5].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[6].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader")
                }
            );

            table.Rows.Add(rowHeader);
            try
            {
                if (lvAndPeoNumList == null || lvAndPeoNumList.Count == 0)
                {
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    //labelCountOfUser.Text = string.Format("{0:N0}", dt.Rows.Count);
                    string css;
                    int stt = 0;
                    foreach (LevelAndPeopleNum dr in lvAndPeoNumList)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();
                        row.Cells.AddRange
                        (
                            new TableCell[]
                           {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Level),HorizontalAlign.Left,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.PeopleNum),HorizontalAlign.Left,css)
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[5].ColumnName]),HorizontalAlign.Left,css),
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[6].ColumnName]),HorizontalAlign.Left,css),

                           }
                        );

                        table.Rows.Add(row);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return table;
        }
        private Table getLevelLoss2(List<Au> auData)
        {
            List<Au> auList = new List<Au>(auData.Count);

            auData.ForEach((item) =>
            {
                auList.Add(new Au(item));
            });

            //foreach (Au auItem in auList)
            //{
            //    auItem.Timestamp = ConverterWorkData.truncateTime(auItem.Timestamp, "dd/MM/yyyy");
            //}

            var timeList = (from tb2 in auList select tb2.Timestamp).Distinct().ToList();
            timeList.Sort();

            string countTime = ConverterWorkData.truncateTime(ConverterWorkData.kindDateTimeToKindUnixTimestamp(IDAdmin.Common.ConverterWorkData.convertStringToDateTime(txtCountDate.Text), DateTimeKind.Local).ToString(), "dd/MM/yyyy");

            var accountAtTimeList = new[] { new { Account = "" } }.ToList();
            accountAtTimeList.RemoveAt(0);
            foreach (var item in auList)
            {
                if (item.Timestamp.Equals(countTime) && item.GameZone.Equals("1004"))//2491372 là thiên long
                {
                    accountAtTimeList.Add(new { Account = item.Account });
                }
            }
            accountAtTimeList = accountAtTimeList.Distinct().ToList();


            var checkDayNum = (from tb in timeList.AsParallel() where tb.CompareTo(countTime) > 0 select tb).Count().ToString();

            List<LevelAndPeopleNum> lvAndPeoNumList = new List<LevelAndPeopleNum>();

            if (int.Parse(checkDayNum) >= 7)
            {
                DateTime dtTemp = ConverterWorkData.kindUnixTimeStampToKindDateTime(double.Parse(countTime), DateTimeKind.Local, DateTimeKind.Local);
                DateTime nextDtTemp = dtTemp.AddDays(1);
                DateTime seventhDay = dtTemp.AddDays(7);

                int count = 0;
                var accountNotLoginAtTimeList = new[] { new { Account = "" } }.ToList();
                accountNotLoginAtTimeList.RemoveAt(0);
                foreach (var item in accountAtTimeList)
                {
                    var hasLogin = (from tb in auList.AsParallel() where tb.Account.Equals(item.Account) && tb.DateTime.CompareTo(nextDtTemp) >= 0 && tb.DateTime.CompareTo(seventhDay) <= 0 select tb).Count().ToString();
                    if (int.Parse(hasLogin) <= 0)
                    {
                        count++;
                        accountNotLoginAtTimeList.Add(item);
                    }

                }
                //var accountAndLevelList = new[] { new { Account = "", Level = "" } }.ToList();
                //accountAndLevelList.RemoveAt(0);

                foreach (var account in accountNotLoginAtTimeList)
                {
                    string url = "http://{0}:{1}/getCharidName?gosuAccount={2}&game=38&zone=1004";
                    url = string.Format(url, hostName, port, account.Account);
                    string result = HttpHelper.HttpSocket(url, 26);
                    if (string.IsNullOrEmpty(result) == false)
                    {
                        if (result.Substring(0, 1).Equals("0"))
                        {
                            JavaScriptSerializer jss = new JavaScriptSerializer();
                            CharidName cin = jss.Deserialize<CharidName>(result.Substring(2, result.IndexOf("}", result.IndexOf("name")) - 1));
                            //LevelWebDB.insert_Lau_Table("Lau", dtTemp, account.Account, cin.charid);
                            //string level = LevelWebDB.getLevel(cin.charid, "2015-03-12 00:00:00", dtTemp.ToString("yyyy-MM-dd") + " 23:59:59");
                            //accountAndLevelList.Add(new { Account = account.Account, Level = level });
                        }
                        else
                        {
                            //LevelWebDB.insert_Lau_Table("Lau", dtTemp, account.Account, "");
                        }
                    }
                }


                //lvAndPeoNumList = (from tb in accountAndLevelList where string.IsNullOrEmpty(tb.Level) == false group tb by new { tb.Level } into grp select new LevelAndPeopleNum { Level = grp.Key.Level, PeopleNum = grp.Count().ToString() }).OrderBy(o => int.Parse(o.Level)).ToList();
            }

            Table table = new Table();
            table.CssClass = "table1";
            table.CellSpacing = 1;
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                {     
                    UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                     UIHelpers.CreateTableCell("Level",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                       UIHelpers.CreateTableCell("People Number",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                    //UIHelpers.CreateTableCell("CcuServerList",Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[5].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[6].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader")
                }
            );

            table.Rows.Add(rowHeader);
            try
            {
                if (lvAndPeoNumList == null || lvAndPeoNumList.Count == 0)
                {
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    //labelCountOfUser.Text = string.Format("{0:N0}", dt.Rows.Count);
                    string css;
                    int stt = 0;
                    foreach (LevelAndPeopleNum dr in lvAndPeoNumList)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();
                        row.Cells.AddRange
                        (
                            new TableCell[]
                           {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Level),HorizontalAlign.Left,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.PeopleNum),HorizontalAlign.Left,css)
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[5].ColumnName]),HorizontalAlign.Left,css),
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[6].ColumnName]),HorizontalAlign.Left,css),

                           }
                        );

                        table.Rows.Add(row);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return table;
        }

        public static void cronLevelSave(DateTime date)
        {
            //DateTime date = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(txtCountDate.Text);
            LevelSaveStatsWebDB lls = new LevelSaveStatsWebDB();
            lls.getStatsData(date);
            lls.insertStatsData(lls.getLevelSaveStats(date), date);
            //List<LevelAndPeopleNum> lvAndPeoNumList = lls.getStatsData(date); 
            //lls.insertStatsData(lvAndPeoNumList, date);
        }
        private Table getLevelSaveStatsTable(DateTime date)
        {
            //DateTime date = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(txtCountDate.Text);
            LevelSaveStatsWebDB lls = new LevelSaveStatsWebDB();
            lls.getStatsData(date);
            List<LevelAndPeopleNum> lvAndPeoNumList = lls.getLevelSaveStats(date).OrderBy(o => int.Parse(o.Level)).ToList();
            lls.insertStatsData(lvAndPeoNumList, date);
            //List<LevelAndPeopleNum> lvAndPeoNumList = lls.getStatsData(date).OrderBy(o => int.Parse(o.Level)).ToList(); 
            //lls.insertStatsData(lvAndPeoNumList, date);

            Table table = new Table();
            table.CssClass = "table1";
            table.CellSpacing = 1;
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                {     
                    UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                     UIHelpers.CreateTableCell("Level",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                       UIHelpers.CreateTableCell("People Number",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                    //UIHelpers.CreateTableCell("CcuServerList",Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[5].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[6].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader")
                }
            );

            table.Rows.Add(rowHeader);
            try
            {
                if (lvAndPeoNumList == null || lvAndPeoNumList.Count == 0)
                {
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    //labelCountOfUser.Text = string.Format("{0:N0}", dt.Rows.Count);
                    string css;
                    int stt = 0;
                    foreach (LevelAndPeopleNum dr in lvAndPeoNumList)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();
                        row.Cells.AddRange
                        (
                            new TableCell[]
                           {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Level),HorizontalAlign.Left,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.PeopleNum),HorizontalAlign.Left,css)
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[5].ColumnName]),HorizontalAlign.Left,css),
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[6].ColumnName]),HorizontalAlign.Left,css),

                           }
                        );

                        table.Rows.Add(row);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return table;
        }

        public static void cronLevelLoss(DateTime date)
        {
            //DateTime date = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(txtCountDate.Text);
            LossLevelStats lls = new LossLevelStats();
            lls.getAccountAtTimeList(date);
            lls.getDataStats(date);
            lls.insertLevelLoss(lls.getLevelLossStats(date),date);
            //List<LevelAndPeopleNum> lvAndPeoNumList = lls.getDataStats(date);
            //lls.insertLevelLoss(lvAndPeoNumList, date);
        }
        private Table getLevelLossStatsTable(DateTime date)
        {
            //DateTime date = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(txtCountDate.Text);
            LossLevelStats lls = new LossLevelStats();
            lls.getAccountAtTimeList(date);
            lls.getDataStats(date);
            List<LevelAndPeopleNum> lvAndPeoNumList = lls.getLevelLossStats(date).OrderBy(o => int.Parse(o.Level)).ToList();
            lls.insertLevelLoss(lvAndPeoNumList, date);
            //List<LevelAndPeopleNum> lvAndPeoNumList = lls.getDataStats(date).OrderBy(o => int.Parse(o.Level)).ToList();
            //lls.insertLevelLoss(lvAndPeoNumList,date);

            Table table = new Table();
            table.CssClass = "table1";
            table.CellSpacing = 1;
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                {     
                    UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                     UIHelpers.CreateTableCell("Level",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                       UIHelpers.CreateTableCell("People Number",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                    //UIHelpers.CreateTableCell("CcuServerList",Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[5].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[6].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader")
                }
            );

            table.Rows.Add(rowHeader);
            try
            {
                if (lvAndPeoNumList == null || lvAndPeoNumList.Count == 0)
                {
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    //labelCountOfUser.Text = string.Format("{0:N0}", dt.Rows.Count);
                    string css;
                    int stt = 0;
                    foreach (LevelAndPeopleNum dr in lvAndPeoNumList)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();
                        row.Cells.AddRange
                        (
                            new TableCell[]
                           {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Level),HorizontalAlign.Left,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.PeopleNum),HorizontalAlign.Left,css)
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[5].ColumnName]),HorizontalAlign.Left,css),
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[6].ColumnName]),HorizontalAlign.Left,css),

                           }
                        );

                        table.Rows.Add(row);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return table;
        }
        protected void buttonCountSave_Click(object sender, EventArgs e)
        {

            dataPanel.Controls.Clear();
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            DateTime date = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(txtCountDate.Text);
            if (countTypeDropDownList.SelectedItem.Value.Equals("0"))
            {
                dataPanel.Controls.Add(getLevelLossStatsTable(date));
            }
            else
            {
                dataPanel.Controls.Add(getLevelSaveStatsTable(date));
            }
            watch.Stop();
            double elapsedMS = watch.ElapsedMilliseconds;
            measureLB.Text = elapsedMS.ToString() + "miliseconds";
        }

        private Table getFastLevelLossTable(DateTime date)
        {
            //DateTime date = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(txtCountDate.Text);
            LossLevelStats lls = new LossLevelStats();
            //List<LevelAndPeopleNum> lvAndPeoNumList =lls.getLevelLossData(date.ToString("yyyy-MM-dd") + " 00:00:00", date.ToString("yyyy-MM-dd" + " 23:59:59"));
            List<LevelAndPeopleNum> lvAndPeoNumList = lls.getFastLevelLossData(date.ToString("yyyy-MM-dd")+" 00:00:00",date.ToString("yyyy-MM-dd")+ " 23:59:59");
            lvAndPeoNumList = lvAndPeoNumList.OrderBy(o => int.Parse(o.Level)).ToList();

            Table table = new Table();

            table.CssClass = "table1";
            table.CellSpacing = 1;
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                {     
                    UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                     UIHelpers.CreateTableCell("Level",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                       UIHelpers.CreateTableCell("People Number",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                    //UIHelpers.CreateTableCell("CcuServerList",Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[5].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[6].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader")
                }
            );

            table.Rows.Add(rowHeader);
            try
            {
                if (lvAndPeoNumList == null || lvAndPeoNumList.Count == 0)
                {
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    //labelCountOfUser.Text = string.Format("{0:N0}", dt.Rows.Count);
                    string css;
                    int stt = 0;
                    int sum = 0;
                    foreach (LevelAndPeopleNum dr in lvAndPeoNumList)
                    {
                        sum += Converter.ToInt(dr.PeopleNum);
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();
                        row.Cells.AddRange
                        (
                            new TableCell[]
                           {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Level),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.PeopleNum),HorizontalAlign.Center,css)
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[5].ColumnName]),HorizontalAlign.Left,css),
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[6].ColumnName]),HorizontalAlign.Left,css),

                           }
                        );

                        table.Rows.Add(row);
                    }
                    TableRow endrow = new TableRow();
                    endrow.Cells.AddRange
                    (
                        new TableCell[]
                           {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,"cell1"),
                                    UIHelpers.CreateTableCell("",HorizontalAlign.Center,"cell1"),
                                    UIHelpers.CreateTableCell(sum.ToString(),HorizontalAlign.Center,"cell1")
                           }
                    );

                    table.Rows.Add(endrow);
                }
            }
            catch (Exception ex)
            {
            }
            return table;
        }

        private Table getFastLevelSaveTable(DateTime date)
        {
            //DateTime date = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(txtCountDate.Text);
            LevelSaveStatsWebDB lssWebDB = new LevelSaveStatsWebDB();
            List<LevelAndPeopleNum> lvAndPeoNumList = lssWebDB.getFastStatsData(date.ToString("yyyy-MM-dd") + " 00:00:00", date.ToString("yyyy-MM-dd") + " 23:59:59").OrderBy(o => int.Parse(o.Level)).ToList(); ;
            //List<LevelAndPeopleNum> lvAndPeoNumList = lssWebDB.getFastStatsData(date.ToString("yyyy-MM-dd") + " 00:00:00", date.ToString("yyyy-MM-dd" + " 23:59:59"));
            //lvAndPeoNumList = lvAndPeoNumList.OrderBy(o => int.Parse(o.Level)).ToList();
            Table table = new Table();
            table.CssClass = "table1";
            table.CellSpacing = 1;
            TableRow rowHeader = new TableRow();
            rowHeader.Cells.AddRange
            (
                new TableCell[]
                {     
                    UIHelpers.CreateTableCell("STT",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                     UIHelpers.CreateTableCell("Level",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader"),
                       UIHelpers.CreateTableCell("People Number",Unit.Percentage(5), HorizontalAlign.Center,"cellHeader")
                    //UIHelpers.CreateTableCell("CcuServerList",Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[5].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader"),  
                    //UIHelpers.CreateTableCell(dt.Columns[6].ColumnName,Unit.Percentage(6),HorizontalAlign.Center, "cellHeader")
                }
            );

            table.Rows.Add(rowHeader);
            try
            {
                if (lvAndPeoNumList == null || lvAndPeoNumList.Count == 0)
                {
                    TableRow rowEmpty = new TableRow();
                    rowEmpty.Cells.Add(UIHelpers.CreateTableCell("<p>Không có dữ liệu!</p>", HorizontalAlign.Center, "cell1", 4));
                    table.Rows.Add(rowEmpty);
                }
                else
                {
                    //labelCountOfUser.Text = string.Format("{0:N0}", dt.Rows.Count);
                    string css;
                    int stt = 0;
                    foreach (LevelAndPeopleNum dr in lvAndPeoNumList)
                    {
                        stt += 1;
                        css = stt % 2 == 0 ? "cell1" : "cell2";
                        TableRow row = new TableRow();
                        row.Cells.AddRange
                        (
                            new TableCell[]
                           {
                                    UIHelpers.CreateTableCell(stt.ToString(),HorizontalAlign.Center,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.Level),HorizontalAlign.Left,css),
                                    UIHelpers.CreateTableCell(Converter.ToString(dr.PeopleNum),HorizontalAlign.Left,css)
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[5].ColumnName]),HorizontalAlign.Left,css),
                                    //UIHelpers.CreateTableCell(Converter.ToString(dr[dt.Columns[6].ColumnName]),HorizontalAlign.Left,css),

                           }
                        );

                        table.Rows.Add(row);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return table;
        }
        protected void buttonCountLL_Click(object sender, EventArgs e)
        {
            dataPanel.Controls.Clear();
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();
            DateTime date = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(txtCountDate.Text);
            if (countTypeDropDownList.SelectedItem.Value.Equals("0"))
            {
                dataPanel.Controls.Add(getFastLevelLossTable(date));
            }
            else
            {
                dataPanel.Controls.Add(getFastLevelSaveTable(date));
            }
            watch.Stop();
            double elapsedMS = watch.ElapsedMilliseconds;
            measureLB.Text = elapsedMS.ToString() + "miliseconds";
        }

        protected void ButtonCountAndSaveFrDateToDate_Click(object sender, EventArgs e)
        {
            DateTime dtFormDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(CountToolBar.beginDateTextBox.Text);
            DateTime dtToDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(CountToolBar.toDateTextBox.Text);
            List<DateTime> dateTimeList = IDAdmin.Common.ConverterWorkData.getDateListBetween(dtFormDate, dtToDate);
            if (countTypeDropDownList.SelectedItem.Value.Equals("0"))
            {
                foreach (DateTime date in dateTimeList)
                {
                    getLevelLossStatsTable(date);
                }
            }
            else
            {
                foreach (DateTime date in dateTimeList)
                {
                    getLevelSaveStatsTable(date);
                }
            }
        }
        private void insertDisLevel()
        {       
            DateTime dtFormDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(CountToolBar.beginDateTextBox.Text);
            DateTime dtToDate = IDAdmin.Common.ConverterWorkData.convertStringToDateTime(CountToolBar.toDateTextBox.Text);
            List<DateTime> dateTimeList = IDAdmin.Common.ConverterWorkData.getDateListBetween(dtFormDate, dtToDate);
            if (countTypeDropDownList.SelectedItem.Value.Equals("0"))
            {
                foreach (DateTime date in dateTimeList)
                {
                    LossLevelStats lls = new LossLevelStats();
                    lls.insertLevelLoss(lls.getLevelLossStats(date),date);
                }
            }
            else
            {
                foreach (DateTime date in dateTimeList)
                {
                    LevelSaveStatsWebDB lssWebDB = new LevelSaveStatsWebDB();
                    lssWebDB.insertStatsData(lssWebDB.getLevelSaveStats(date),date);

                }
            }
        }
        protected void ButtonCountSaveDisLevel_Click(object sender, EventArgs e)
        {
            insertDisLevel();
        }

    }
}